//
//  SetRateVC.swift
//  kxf
//
//  Created by Elavatine on 2024/11/6.
//


import Foundation
import MCToast

class SetRateVC: WHBaseViewVC {
    
    var phone = ""
    var isMerc = false
    var isAgent = false
    var isFromCenterTabbar = false
    var dataArr = NSArray()
    var channelListArray = NSArray()
    var channel = "ys"
    
    var dataSubmitArray = NSMutableArray()
    
    var vmDataArray = NSMutableArray()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initUI()
        if isAgent {
            view.addSubview(channelVm)
            sendChannelListRequest()
//            getRateInfoRequestAgent()
        }else{
            getRateInfoRequest()
            vmScrollView.frame = CGRect.init(x: 0, y: getNavigationBarHeight()+kFitWidth(10), width: SCREEN_WIDHT, height: SCREEN_HEIGHT-getBottomSafeAreaHeight()-getNavigationBarHeight()-kFitWidth(20))
        }
        view.addSubview(vmScrollView)
        vmScrollView.addSubview(nextBtn)
    }
    lazy var channelVm: SetRatePosChannelVM = {
        let vm = SetRatePosChannelVM.init(frame: CGRect.init(x: 0, y: getNavigationBarHeight()+kFitWidth(1), width: 0, height: 0))
        vm.tapBlock = {(posChannel)in
            if posChannel.count > 0 {
                self.channel = posChannel
            }else{
                self.channel = "ys"
            }
            self.getRateInfoRequestAgent()
        }
        return vm
    }()
    lazy var vmScrollView: UIScrollView = {
        let scro = UIScrollView(frame: CGRect.init(x: 0, y: self.channelVm.frame.maxY+kFitWidth(10), width: SCREEN_WIDHT, height: SCREEN_HEIGHT-getBottomSafeAreaHeight()-self.channelVm.frame.maxY-kFitWidth(20)))
        
        return scro
    }()
    lazy var nextBtn : UIButton = {
        let btn = UIButton()
        btn.setTitle("确认", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.setBackgroundImage(UIImage.init(named: "button_theme_bg"), for: .normal)
        btn.layer.cornerRadius = kFitWidth(24)
        btn.clipsToBounds = true
        btn.titleLabel?.font = .systemFont(ofSize: 16, weight: .regular)
        btn.backgroundColor = .clear
        
        btn.addTarget(self, action: #selector(submitAction), for: .touchUpInside)
        
        return btn
    }()
}

extension SetRateVC{
    @objc func submitAction(){
        if checkValue(){
            sendSetRateInfoRequest()
        }
    }
    func checkValue() -> Bool {
        dataSubmitArray = NSMutableArray()
        for i in 0..<vmDataArray.count {
            let vm = vmDataArray[i]as! SetRateMsgItemVM
            let feeNum = vm.feeTextField.text
            let extraNum = vm.extraTextField.text
            
            if feeNum?.floatValue ?? 0 == 0 || feeNum == ""{
                MCToast.mc_text("\(vm.leftTitleLabel.text ?? "")费率不能为空")
                return false
            }
            let dictT = dataArr[i]as? NSDictionary ?? [:]
            
            if feeNum?.floatValue ?? 0 > Float(dictT["channelRateMax"]as? Double ?? 0.00) || feeNum?.floatValue ?? 0 < Float(dictT["channelRateMin"]as? Double ?? 0.00){
                MCToast.mc_text("\(vm.leftTitleLabel.text ?? "")费率范围 \(vm.feeAreaLabel.text ?? "")")
                return false
            }
            
            if extraNum?.floatValue ?? 0 > Float(dictT["channelSettlementMax"]as? Double ?? 0.00) || extraNum?.floatValue ?? 0 < Float(dictT["channelSettlementMin"]as? Double ?? 0.00){
                MCToast.mc_text("\(vm.leftTitleLabel.text ?? "")手续费范围 \(vm.extraAreaLabel.text ?? "")")
                return false
            }
            
            let dict = NSMutableDictionary.init(dictionary: dictT)
            dict.setValue("\(feeNum ?? "")", forKey: "channelRate")
            dict.setValue("\(extraNum ?? "")", forKey: "channelSettlement")
            dict.setValue("\(dictT["productName"]as? String ?? "")", forKey: "channel")
            dict.setValue(false, forKey: "showFee")
            dict.setValue(false, forKey: "showLement")
            dict.setValue(false, forKey: "showRate")
            
            dataSubmitArray.add(dict)
        }
        return true
    }
}
extension SetRateVC{
    func initUI() {
        if isMerc{
            initNavi(titleStr: "商户费率")
        }else{
            if isAgent {
                initNavi(titleStr: "服务商费率")
            }else{
                initNavi(titleStr: "设置费率")
            }
        }
        
        view.backgroundColor = .COLOR_LIGHT_GREY
        
    }
    func refreshUI() {
        for vi in vmScrollView.subviews{
            if vi.isKind(of: SetRateMsgItemVM.self){
                vi.removeFromSuperview()
            }
        }
        
//        nextBtn.removeFromSuperview()
        vmDataArray.removeAllObjects()
        
//        let originY = isAgent ? self.channelVm.frame.maxY + kFitWidth(10) : getNavigationBarHeight()+kFitWidth(10)
        let originY = kFitWidth(10)
        for i in 0..<dataArr.count{
            let dict = dataArr[i]as? NSDictionary ?? [:]
            let vm = SetRateMsgItemVM.init(frame: CGRect.init(x: 0, y: originY+SetRateMsgItemVM().selfHeight*CGFloat(i), width: 0, height: 0))
            vmScrollView.addSubview(vm)
            vm.refreshUI(dict: dict,isMerc:self.isMerc)
            vm.tag = 3030 + i
            
            if self.isFromCenterTabbar || self.isMerc{
                vm.refreshUIForMerc()
            }
            
            vmDataArray.add(vm)
        }
        vmScrollView.contentSize = CGSize.init(width: 0, height: originY+SetRateMsgItemVM().selfHeight*CGFloat(dataArr.count)+kFitWidth(20))
        if !isMerc{
//            vmScrollView.addSubview(nextBtn)
            nextBtn.isHidden = false
            nextBtn.frame = CGRect.init(x: kFitWidth(31), y: originY+SetRateMsgItemVM().selfHeight*CGFloat(dataArr.count)+kFitWidth(68), width: kFitWidth(316), height: kFitWidth(48))
            vmScrollView.contentSize = CGSize.init(width: 0, height: originY+SetRateMsgItemVM().selfHeight*CGFloat(dataArr.count)+kFitWidth(130))
        }else{
            nextBtn.isHidden = true
        }
        
        if isFromCenterTabbar{
            nextBtn.isHidden = true
            vmScrollView.contentSize = CGSize.init(width: 0, height: originY+SetRateMsgItemVM().selfHeight*CGFloat(dataArr.count)+kFitWidth(20))
        }
    }
}

extension SetRateVC{
    func getRateInfoRequest() {
        MCToast.mc_loading()
        let urlString = "\(URL_get_pos_rateTemplate)?phone=\(phone)&type=0&posChannel=ys"
        WHNetworkUtil.shareManager().GET(urlString: urlString) { response in
            DLLog(message: "\(response)")
            MCToast.mc_remove()
            let dataDict = response["data"]as? NSDictionary ?? [:]
            self.dataArr = dataDict["list"]as? NSArray ?? []
            self.refreshUI()
        }
    }
    func sendChannelListRequest() {
        WHNetworkUtil.shareManager().POST(urlString: URL_authen_channel_list, parameters: nil) { responseObject in
            DLLog(message: "\(responseObject)")
            self.channelListArray = responseObject["data"]as? NSArray ?? []
            self.channelVm.setChannelDataArray(array: self.channelListArray)
            let dict = self.channelListArray.firstObject as? NSDictionary ?? [:]
            self.channel = dict["code"]as? String ?? ""
            self.getRateInfoRequestAgent()
//            self.choiceChannelAlertVm.updateUI(array: dataArr)
        }
    }
    func getRateInfoRequestAgent() {
        MCToast.mc_loading()
        let urlString = "\(URL_get_pos_rateTemplate)?phone=\(phone)&type=1&posChannel=\(channel)"
        WHNetworkUtil.shareManager().GET(urlString: urlString) { response in
            DLLog(message: "\(response)")
            MCToast.mc_remove()
            let dataDict = response["data"]as? NSDictionary ?? [:]
            self.dataArr = dataDict["list"]as? NSArray ?? []
            self.refreshUI()
        }
    }
    func sendSetRateInfoRequest() {
        let type = isAgent ? "1" : "0"
        let param = ["list":dataSubmitArray,
                     "phone":"\(phone)",
                     "type":"\(type)",
                     "freezeAmount":"0",
                     "channel":"\(self.channel)"] as [String : Any]
        WHNetworkUtil.shareManager().POST(urlString: URL_modify_pos_rate, parameters: param as [String : AnyObject],isNeedToast: true,vc: self) { responseObject in
            DLLog(message: "\(responseObject)")
            MCToast.mc_text("费率设置成功！")
        }
    }
}
